import MathUtils from "./MathUtil";
import SystemConfig from "./SystemConfig";
import SystemDataSys from "./SystemDataSys";

import i from "./PageMgr"
const { ccclass, property } = cc._decorator;

@ccclass
class EngineUtil {
    private static _instance: EngineUtil;
    public toastContent = "";
    public color = new cc.Color();
    public currSeed = new Date().getTime();
    public manageToast = null;
    public manageShows = 0;

    static _getInstance() {
        if (!EngineUtil._instance) {
            EngineUtil._instance = new EngineUtil();
        }
        return EngineUtil._instance;
    }

    public localStorageGetItem(e, t) {
        var a = cc.sys.localStorage.getItem(e);
        return a && "" != a && null != a && "nan" != a ? a : t;
    };

    public localStorageSetItem(e, t) {
        cc.sys.localStorage.setItem(e, t);
    };

    public getColor(e) {
        if (!e.includes("#")) {
            e = "#" + e;
        }
        return this.color.fromHEX(e);
    };

    public log() {
        for (var e = [], t = 0; t < arguments.length; t++) {
            e[t] = arguments[t];
        }
        if (!SystemConfig.online_release) {
            if (cc.sys.isNative) {
                try {
                    console.log(SystemDataSys.GAME_NAME, JSON.stringify(e));
                } catch (e) {
                    console.error(SystemDataSys.GAME_NAME, e);
                }
            } else {
                console.log(SystemDataSys.GAME_NAME, e);
            }
        }
    };

    public error() {
        // for (var e = [], t = 0; t < arguments.length; t++) {
        //     e[t] = arguments[t];
        // }
        // if (!SystemConfig.online_release) {
        //     if (cc.sys.isNative) {
        //         try {
        //             console.error(SystemDataSys.GAME_NAME, JSON.stringify(e));
        //         } catch (e) {
        //             console.error(SystemDataSys.GAME_NAME, e);
        //         }
        //     } else {
        //         console.error(SystemDataSys.GAME_NAME, e);
        //     }
        // }
    };

    public setLocalData(e, t) {
        cc.sys.localStorage.setItem(e, t);
    };

    public getLocalData(e) {
        return cc.sys.localStorage.getItem(e) || "";
    };

    public getRandId() {
        return Number(Math.random().toString().substr(3, 3) + Date.now()).toString(36);
    };

    public getTimeStamp() {
        return Math.floor(Date.now() / 1e3);
    };

    public destroyNode(e) {
        if (cc.isValid(e)) {
            e.removeFromParent(false);
            e.destroy();
        } else {
            console.error("Tools:destroyNode error, param is invalid");
        }
    };

    public isLargeScreen() {
        var e = cc.winSize.height / cc.winSize.width;
        return Number(e.toFixed(2)) > 2;
    };

    public getBottomPosY() {
        var e = -cc.winSize.height / 2;
        if (this.isLargeScreen()) {
            e += 30;
        }
        return e;
    };

    public getTopPosY() {
        var e = cc.winSize.height / 2;
        if (this.isLargeScreen()) {
            e -= 65;
        }
        return e;
    };

    public loadRemoteAsset(e) {
        return new Promise(function (t, a) {
            cc.assetManager.loadRemote(e, function (o, i) {
                if (o) {
                    console.error("加载远程资源错误 url:" + e, o);
                    a();
                } else {
                    t(i);
                }
            });
        });
    };

    public loadRemoteImg(e) {
        return new Promise(function (t, a) {
            cc.assetManager.loadRemote(e, { ext: ".png" }, function (o, i) {
                if (o) {
                    console.error("加载远程图片资源错误 url:" + e, o);
                    a();
                } else {
                    t(i);
                }
            });
        });
    };

    public loadResourceAsset(e) {
        return new Promise(function (t, a) {
            cc.resources.load(e, function (o, i) {
                if (o) {
                    console.error("加载 resource 错误 url:" + e, o);
                    a(o);
                } else {
                    t(i);
                }
            });
        });
    };

    public formatTime(e) {
        var t = Math.floor(e / 60 << 0),
            a = Math.floor(e % 60);
        t < 10 && (t = "0" + t);
        a < 10 && (a = "0" + a);
        return t + ":" + a;
    };

    public formatDate(e, t?) {
        void 0 === t && (t = "-");
        var a = new Date(e);
        return "" + a.getFullYear() + t + (a.getMonth() + 1) + t + a.getDate();
    };

    public getRandomNum(e, t) {
        return Math.floor(Math.random() * (t - e + 1)) + e;
    };

    public getRandomNumber(e, t) {
        return Math.floor(Math.random() * (t - e)) + e;
    };

    public getProgressWidth(e, t, a) {
        var o = e < .5 ? Math.ceil(e * a) : Math.floor(e * a);
        0 != o && o < t && (o = t);
        o > a && (o = a);
        var i = Math.floor(100 * e);
        isNaN(i) && (i = 1);
        return { width: o, persent: i };
    };

    public getPosByRot(e, t) {
        var a = e * Math.cos(2 * Math.PI / 360 * (90 - t)),
            o = e * Math.sin(2 * Math.PI / 360 * (90 - t));
        return cc.v2(a, o);
    };

    public GetChildByName(e, t, a) {
        var o = e.node ? e.node : e,
            i = null;
        if (o && t) {
            i = o.getChildByName(t);
            if (a && !i) {
                for (var r = o.children, n = o.childrenCount, l = 0; l < n && !(i = this.GetChildByName(r[l], t, a)); ++l);
            }
        }
        return i;
    };

    public range(e, t) {
        t = t || 1;
        e = e || 0;
        this.currSeed = (9301 * this.currSeed + 49297) % 233280;
        var a = this.currSeed / 233280;
        return parseInt((e + a * (t - e)).toString());
    };

    public convertNodePosition(e, t) {
        if (e && e.parent && t && t.parent) {
            var a = e.parent.convertToNodeSpaceAR(t.parent.convertToWorldSpaceAR(t.position));
            return a;
        }
        return { x: 0, y: 0 };
    };

    public getNodeAToNodeBPoint(e, t) {
        if (e && t && t.parent) {
            var a = e.convertToWorldSpaceAR(cc.Vec2.ZERO),
                o = t.parent.convertToNodeSpaceAR(a);
            return { x: o.x, y: o.y };
        }
        return { x: 0, y: 0 };
    };

    public GetPrize(e) {
        for (var t = e.reduce(function (e, t) {
            return e + t;
        }, 0), a = Math.ceil(Math.random() * t), o = 0, i = 0; i < e.length; i++) {
            if (a <= (o += e[i])) {
                return i;
            }
        }
    };

    public showManageViewToast(e?, t?, a?, o?) {
        debugger
        var r = this;
        void 0 === e && (e = "");
        void 0 === t && (t = .8);
        void 0 === a && (a = true);
        void 0 === o && (o = cc.v3());
        if (e && (!(this.manageShows > 0) || a)) {
            if (this.manageToast) {
                var n = cc.instantiate(this.manageToast);
                i.setToastNode(n);
                n.position = o;
                n.getChildByName("content").getChildByName("text").getComponent(cc.Label).string = e;
                n.zIndex = 999;
                this.manageShows++;
                n.runAction(cc.sequence(cc.moveBy(t, 0, 100), cc.delayTime(1), cc.fadeOut(.3), cc.callFunc(function () {
                    n.parent = null;
                    n.destroy();
                    r.manageShows--;
                })));
            } else {
                cc.loader.loadRes("prefabs/ManageToast", cc.Prefab, function (i, n) {
                    if (!i) {
                        r.manageToast = n;
                        r.showManageViewToast(e, t, a, o);
                    }
                });
            }
        }
    };

    public randomsInt(e, t, a) {
        var o;
        a > t - e && (a = t - e);
        for (var i = Array.from({ length: t - e }, function (t, a) {
            return a + e;
        }), r = 0; r < a; r++) {
            var n = Math.floor(Math.random() * (i.length - r) + r);
            o = [i[n], i[r]], i[r] = o[0], i[n] = o[1];
        }
        i.length = a;
        return i;
    };

    public shuffle(e) {
        for (var t, a = e.length; a;) {
            var o = Math.floor(Math.random() * a--);
            t = [e[a], e[o]], e[o] = t[0], e[a] = t[1];
        }
        return e;
    };

    public subUserName(e, t) {
        void 0 === t && (t = 8);
        return "" != e && e.length > t ? e.substring(0, t) : e;
    };

    public deepClone(e, t) {
        for (var a in t) {
            if ("object" == typeof t[a]) {
                e[a] = {};
                this.deepClone(e[a], t[a]);
            } else {
                e[a] = t[a];
            }
        }
    };

    public getRandomArrayElements(e, t) {
        if (t > e.length) {
            console.error("数量大于数组数");
            return e;
        }
        if (t === e.length) return e;
        for (var a = [], o = 0; o < t; o++) {
            var i = Math.floor(Math.random() * e.length),
                r = e[i];
            a.push(r);
            e.splice(i, 1);
        }
        return a.reverse();
    };

    public getRandomArrayElements2(e, t) {
        if (t > e.length) {
            console.error("数量大于数组数");
            return e;
        }
        for (var a = [], o = 0; o < t; o++) {
            var i = Math.floor(Math.random() * e.length),
                r = e[i];
            a.push(r);
            e.splice(i, 1);
        }
        return a.reverse();
    };

    public shuffleArr2(e) {
        var t = e.map( (e) => {
            return { v: e, r: Math.random() };
        });
        t.sort(function (e, t) {
            return e.r - t.r;
        });
        e.splice.apply(e, [0, e.length].concat(t.map( (e) => {
            return e.v;
        })));
        return e;
    };

    public getCashBalance(e) {
        // if (0 == e) return e.toString();
        // var t = Math.floor(100 * e) / 100 / 100,
        //     a = parseInt(t.toString()),
        //     o = a.toString(),
        //     i = parseInt((MathUtils.accMul(t, 100) - 100 * a).toString()).toString();
        // 1 == i.length && (i = "0" + i);
        // if ("00" == i) return o;
        // 2 == i.length && "0" == i[1] && (i = i[0]);
        // return o + "." + i;
        return e;
    };

    public thousandsNum(e, t) {
        void 0 === t && (t = ".");
        for (var a = "", o = 0, i = (e = (e || 0).toString()).length - 1; i >= 0; i--) {
            o++;
            a = e.charAt(i) + a;
            o % 3 || 0 == i || (a = t + a);
        }
        return a;
    };

    public addLocalJson(e, t) {
        cc.loader.loadRes(e, function (e, a) {
            if (e) {
                console.log("addLocalJson=====", e);
            } else if (a) {
                var o = a.json;
                t && t(o);
            }
        });
    };

    public playSpine(e, t, a, o?) {
        if (e) {
            if (t) {
                if (e.setAnimation(0, t, a)) {
                    e.setCompleteListener(function () {
                        o && o();
                    });
                } else {
                    cc.error('动画不存在======"', t);
                }
            } else {
                cc.error("动画名称不存在======");
            }
        } else {
            cc.error("spine不存在======");
        }
    };

    public formatDecimal(e, t) {
        void 0 === t && (t = 2);
        var a = (e = e.toString()).indexOf(".");
        e = -1 !== a ? e.substring(0, t + a + 1) : e.substring(0);
        return parseFloat(e).toFixed(t);
    };

    public typingAni(e, t, a, o) {
        for (var i = /<.+?\/?>/g, r = t.match(i), n = t.replace(i, "│").split("│"), l = [], s = 0, c = 0; c < n.length; c++) {
            if ("" !== (_ = n[c])) {
                _ = "$[" + s + "]";
                s += 1;
            }
            l.push(_);
        }
        for (var u = l.join("│"), p = [], d = new Array(s).fill(""), h = 0; h < n.length; h++) {
            var f = 0,
                g = n[h];
            for (var y = 0, m = g; y < m.length; y++) {
                var _ = m[y];
                f = f + _;
                var v = u;
                for (var b = 0; b < s; b++) {
                    v = v.replace("$[" + b + "]", d[b]);
                }
                p.push(v);
            }
        }

        var C = 0;

        function T() {
            if (C >= p.length) {
                o && o();
            } else {
                e.string = p[C];
                C += 1;
                setTimeout( () =>{
                    T();
                }, a);
            }
        };

        setTimeout( () =>{
            T();
        }, a);
    };

    public clone(e) {
        if (!cc.sys.isNative) {
            var t;
            if ("object" == typeof e) {
                if (null === e) {
                    t = null;
                } else if (e instanceof Array) {
                    t = [];
                    for (var a = 0, o = e.length; a < o; a++) {
                        t.push(this.clone(e[a]));
                    }
                } else {
                    t = {};
                    for (var i in e) {
                        t[i] = this.clone(e[i]);
                    }
                }
            } else {
                t = e;
            }
            return t;
        }
    };

    public isEmpty(e) {
        switch (e) {
            case null:
            case void 0:
                return true;
            default:
                return false;
        }
    };
}

export default EngineUtil._getInstance();